package com.ccp.learning.udp.core;

import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicLong;

public class MonitoringCenter {
    private static final AtomicLong totalReceived = new AtomicLong(0);
    private static final AtomicLong successCount = new AtomicLong(0);
    private static final AtomicLong errorCount = new AtomicLong(0);
    private static final ConcurrentLinkedQueue<Long> latencyQueue =
            new ConcurrentLinkedQueue<>();

    public static void recordReceived() {
        totalReceived.incrementAndGet();
    }

    public static void recordSuccess(long latencyMs) {
        successCount.incrementAndGet();
        latencyQueue.add(latencyMs);
        if (latencyQueue.size() > 100) latencyQueue.poll();
    }

    public static void recordError() {
        errorCount.incrementAndGet();
    }

    public static void reportMetrics() {
        System.out.println("=== 监控报告 ===");
        System.out.println("总接收量: " + totalReceived.get());
        System.out.println("成功处理: " + successCount.get());
        System.out.println("异常数量: " + errorCount.get());
        System.out.printf("平均延迟: %.2fms\n", calculateAverageLatency());
        System.out.println("===============");
    }

    private static double calculateAverageLatency() {
        return latencyQueue.stream().mapToLong(Long::longValue).average().orElse(0.0);
    }
}